package org.mc.domainservice;

import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.mc.bean.Project;
import org.mc.common.data.ResultData;
import org.mc.common.util.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by luoxf on 2018/6/15.
 */
@Service
public class EsDomainService {

    @Autowired
    private Client client;

    public ResultData list(int pageId, int size) {
        BoolQueryBuilder query = QueryBuilders.boolQuery();
        query.filter(QueryBuilders.termQuery("isOnsale", 1));
        SearchRequestBuilder requestBuilder = client.prepareSearch("newes").setTypes("project")
                .setFrom((pageId - 1) * size).setSize(size)
                .setQuery(query).addSort("onsaleTime", SortOrder.DESC);

        SearchResponse response = requestBuilder.execute().actionGet();

        List list = getResult(response);
        return ResultData.ok(list);
    }

    private List getResult(SearchResponse response) {
        List list = new ArrayList<>();
        if (response.getHits().getTotalHits() > 0) {
            Iterator<SearchHit> iterator2 = response.getHits().iterator();
            while (iterator2.hasNext()) {
                SearchHit hit = iterator2.next();
                String index = hit.getIndex();
                String source = hit.getSourceAsString();
                Object order = JSONObject.parseObject(source, Project.class);
                list.add(order);
            }
        }
        return list;
    }

    public void save(String json) {
        IndexResponse response = client.prepareIndex("newes", "project")
                .setId("1")
                .setSource(json, XContentType.JSON)
                .execute()
                .actionGet();
        System.out.println(JSONUtils.toJson(response));
    }

}
